package com.ys.service.sys.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bo.properties.AppProps;
import com.bo.util.qiniucloud.QiniuCloudUtil;
import com.ys.service.sys.UploadService;

@Service("uploadService")
public class UploadServiceImpl implements UploadService {

//	private static final Logger logger = Logger.getLogger(UploadServiceImpl.class);

	@Override
	public void uploadfileForEditor(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IOException {

		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		if(!ServletFileUpload.isMultipartContent(request)){
			out.println(getError("请选择文件。"));
			return;
		}

//		logger.debug("上传文件");
//		logger.debug("上传文件名 ========" + file.getOriginalFilename());

		/*
		SimpleDateFormat sdfyyyyMMdd = new SimpleDateFormat("/yyyy/MM/dd");
		SimpleDateFormat sdfHHmmssSSS = new SimpleDateFormat("HHmmssSSS");
		Date nowDate = new Date();
		
		// 文件初始名
		String oriFilename = multipartFile.getOriginalFilename();
		
		// .号所在位置
		int lastIndex = oriFilename.lastIndexOf(".");

		// 文件后缀列表
		String imageExts = "gif,jpg,jpeg,png,bmp";
		
		// 扩展名
		String orgFileExt = oriFilename.substring(lastIndex + 1).toLowerCase();

		// 验证扩展名
		if (!imageExts.contains(orgFileExt)) {
			out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + imageExts + "格式。"));
			return;
		}
		
		// 拼接文件名
		String toFilename = sdfHHmmssSSS.format(nowDate) + "." + orgFileExt;
		
		String rootRealPath = System.getProperty("rootRealPath");
		String toRelativePath = "/upload" + sdfyyyyMMdd.format(nowDate);
		String toRealPath = rootRealPath + toRelativePath;
		
		// 创建文件夹
		File toDir = new File(toRealPath + "/");
		if (!toDir.exists()) {
			toDir.mkdirs();
		}

		JSONObject obj = new JSONObject();
		obj.put("error", 0);
		obj.put("url", QiniuProps.get("domain") + toRelativePath + "/" + toFilename);
		
		try {
			InputStream fileInputStream = multipartFile.getInputStream();
			// 将文件保存到本地
			FileOutputStream fs = new FileOutputStream(toRealPath + "/" + toFilename);
			logger.info("------------" + toRealPath + "/" + toFilename);
			byte[] buffer = new byte[1024 * 1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = fileInputStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			fileInputStream.close();
			out.println(obj.toJSONString());
			return;
		} catch (IOException e) {
			e.printStackTrace();
			out.println(getError("上传失败"));
			return;
		}
		*/
		
		SimpleDateFormat sdfyyyyMMdd = new SimpleDateFormat("/yyyy/MM/dd");
		SimpleDateFormat sdfHHmmssSSS = new SimpleDateFormat("HHmmssSSS");
		Date nowDate = new Date();
		
		String rootRealPath = "D:/data";
		String toRelativePath = "/upload" + sdfyyyyMMdd.format(nowDate);
		String toRealPath = rootRealPath + toRelativePath;

		try {
			InputStream fileInputStream = file.getInputStream();
			
			// 文件初始名
			String oriFilename = file.getOriginalFilename();
			
			// .号所在位置
			int lastIndex = oriFilename.lastIndexOf(".");
			
			// 扩展名
			String orgFileExt = oriFilename.substring(lastIndex + 1).toLowerCase();
			
			// 拼接文件名
			String toFilename = sdfHHmmssSSS.format(nowDate) + "." + orgFileExt;
			
			// 将文件保存到本地
			FileOutputStream fs = new FileOutputStream(toRealPath + "/" + toFilename);
			byte[] buffer = new byte[1024 * 1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = fileInputStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			fileInputStream.close();

			JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", "http://localhost:8090" + toRelativePath + "/" + toFilename);
			
			out.println(obj.toJSONString());
			return;
		} catch (IOException e) {
			e.printStackTrace();
			out.println(getError("上传失败"));
			return;
		}
		
	}

	@Override
	public void uploadfileForLayer(HttpServletResponse response, MultipartFile file) throws IOException {

		response.setContentType("text/html; charset=UTF-8");
		Map<String, Object> map = new HashMap<String, Object>();

		PrintWriter out = response.getWriter();
		
		SimpleDateFormat sdfyyyyMMdd = new SimpleDateFormat("/yyyy/MM/dd");
		SimpleDateFormat sdfHHmmssSSS = new SimpleDateFormat("HHmmssSSS");
		Date nowDate = new Date();

		String rootRealPath = "D:/data";
		String toRelativePath = "/upload" + sdfyyyyMMdd.format(nowDate);
		String toRealPath = rootRealPath + toRelativePath;
		
		File dirFile = new File(toRealPath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		try {
			InputStream fileInputStream = file.getInputStream();
			
			// 文件初始名
			String oriFilename = file.getOriginalFilename();
			
			// .号所在位置
			int lastIndex = oriFilename.lastIndexOf(".");
			
			// 扩展名
			String orgFileExt = oriFilename.substring(lastIndex + 1).toLowerCase();
			
			// 拼接文件名
			String toFilename = sdfHHmmssSSS.format(nowDate) + "." + orgFileExt;
			
			// 将文件保存到本地
			FileOutputStream fs = new FileOutputStream(toRealPath + "/" + toFilename);
			byte[] buffer = new byte[1024 * 1024];
			int bytesum = 0;
			int byteread = 0;
			while ((byteread = fileInputStream.read(buffer)) != -1) {
				bytesum += byteread;
				fs.write(buffer, 0, byteread);
				fs.flush();
			}
			fs.close();
			fileInputStream.close();

			JSONObject obj = new JSONObject();
			obj.put("error", 0);
			obj.put("url", "http://localhost:8090" + toRelativePath + "/" + toFilename);
			obj.put("code", 200);
			
			out.println(obj.toJSONString());
			return;
		} catch (IOException e) {
			e.printStackTrace();
			out.println(getError("上传失败"));
			return;
		}
	}
	

	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
}
